﻿using RQX.Common.Framework.Extension;
using RQX.Common.Framework.Hardware.BaseCollection;
using RQX.Common.Framework.Hardware.Com;
using RQX.Common.Framework.Logger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo_COM
{
    public class ComDemo : AbstractComCollection
    {
        public ComDemo(StructureModel<MyCom> structureModel) : base(structureModel)
        {
        }
        /// <summary>
        /// 解析数据
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        protected override Dictionary<string, double> AnalysisData(byte[] buffer)
        {
            return new Dictionary<string, double>()
            {
                {"解析数据1",50 },
                {"解析数据2",60 },
                {"解析数据3",70 },
            };
        }
        /// <summary>
        /// 判断数据是进行到哪一步
        /// </summary>
        /// <param name="lineStr"></param>
        /// <returns></returns>
        protected override StepType CheckRecvMsgType(string lineStr)
        {
            var buffer = lineStr.HexStringToByte();
            switch (buffer[0])
            {
                case 1:return StepType.Setp1;
                case 2:return StepType.Setp2;
                case 3:return StepType.FinishConnect;
                case 0:return StepType.DataSource;
                default:
                    return StepType.Init;
            }
        }
        /// <summary>
        /// 循环采集方法，有必要可写循环，发送采集命令
        /// </summary>
        protected override void CircleSend()
        {
            string sendStr = "05";
            Send(sendStr.HexStringToByte());
        }
        /// <summary>
        /// 连接建立方法
        /// </summary>
        /// <param name="stepNum">当前连接步骤</param>
        protected override void Connect(StepType stepNum)
        {
            switch (stepNum)
            {
                case StepType.Init:
                    Send("00".HexStringToByte());
                    break;
                case StepType.Setp1:
                    Send("01".HexStringToByte());
                    break;
                case StepType.Setp2:
                    Send("02".HexStringToByte());
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 分离收到的数据，根据结束符分割数据
        /// </summary>
        /// <param name="sb"></param>
        /// <returns></returns>
        protected override string CutToOneMsg(StringBuilder sb)
        {
            var allMsg = sb.ToString();
            var index = allMsg.ToUpper().IndexOf("FF");
            if (index > -1)
            {
                return allMsg.Substring(0, index + 2);
            }
            else
            {
                return null;
            }
        }
    }
}
